In SvelteKit, stores are a powerful way to share state between components and even across different routes. Since stores exist outside of the component lifecycle, they persist as long as the app is running, making them ideal for global state management like authentication, theme settings, or user preferences.
First, create a dedicated file for your store in the src/lib directory (or another shared location). This ensures that the store can be imported and used anywhere in the app.
In one route, you can update the store by importing it and using Svelte's reactive set or update methods.
Once the store is updated, its value is accessible from any other route or component by importing the same store.
By default, stores reset when the page is reloaded. If you want to persist data across browser sessions, you can sync the store with localStorage or another storage solution.
Create stores in a shared location like src/lib/stores.
Import the same store file wherever you need it.
Stores persist in memory as long as the app is running, even when switching routes.
For persistence across reloads, sync the store with localStorage or a backend.
Use SvelteKit's $store syntax to auto-subscribe to store values in components.